package com.zh.kotlin_mvvm.ui

import android.Manifest
import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Intent
import android.graphics.Color
import android.media.MediaScannerConnection
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.util.Base64
import android.util.Log
import android.view.Gravity
import android.view.View
import android.widget.FrameLayout
import android.widget.TextView
import androidx.core.app.NotificationManagerCompat
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SizeUtils
import com.zh.common.base.BaseActivity
import com.zh.common.base.BasePopWindow
import com.zh.common.ktx.clickSingleListener
import com.zh.common.ktx.color
import com.zh.common.ktx.dp2px
import com.zh.common.ktx.gotoAct
import com.zh.common.ktx.gotoActAnimation
import com.zh.common.ktx.gotoActDocument
import com.zh.common.ktx.gotoFileAndroid11
import com.zh.common.ktx.launch
import com.zh.common.ktx.liveObserve
import com.zh.common.ktx.livePostValue
import com.zh.common.ktx.moneyFormat
import com.zh.common.ktx.nameFormatNoSpace
import com.zh.common.ktx.registerForResult
import com.zh.common.ktx.toast
import com.zh.common.update.UpdateService
import com.zh.common.utils.CpuArchUtils
import com.zh.common.utils.DoubleUtils
import com.zh.common.utils.EmptyUtils
import com.zh.common.utils.toast.ZToastUtils
import com.zh.common.view.FloatingView
import com.zh.config.PerConfig
import com.zh.config.ZjConfig
import com.zh.kotlin_mvvm.MyApp
import com.zh.kotlin_mvvm.R
import com.zh.kotlin_mvvm.databinding.ActivitySplashBinding
import com.zh.kotlin_mvvm.dialog.TestDialog
import com.zh.kotlin_mvvm.utils.Sm4Util
import kotlinx.coroutines.launch
import me.jessyan.autosize.utils.ScreenUtils
import java.io.File
import java.io.IOException
import java.util.concurrent.CountDownLatch


/**
 * 插件框架：https://github.com/Tencent/Shadow
 * 数据共享：https://blog.csdn.net/weixin_44570190/article/details/134183111
 */
class SplashActivity : BaseActivity<ActivitySplashBinding>(), View.OnClickListener {

    //    override val keyboardListener: OnKeyboardListener = OnKeyboardListener { isPopup, _ ->
//        ZToastUtils.showShort(if (isPopup) "键盘显示" else "键盘隐藏")
//    }
    private val sdcardCamera = if (Build.VERSION.SDK_INT <= 32) {
        listOf(
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.CAMERA
        )
    } else {
        listOf(
            Manifest.permission.READ_MEDIA_IMAGES,
            Manifest.permission.READ_MEDIA_VIDEO,
            Manifest.permission.READ_MEDIA_AUDIO,
            Manifest.permission.CAMERA
        )
    }

    private val launcher = registerForResult {
        it.data?.getStringExtra("name")?.toast()
    }

    override fun initView(savedInstanceState: Bundle?) {
        MyApp.instance.getp2p()?.InitP2PServer()
        ZToastUtils.showShort("启动了")
        val message = "{\"code\":200, \"message\":\"提示内容\",\"data\":{\"content\":\"哈哈哈哈\"}}"
        LogUtils.wTag("okhttp", message)
        LogUtils.wTag("okhttp", "null is ${EmptyUtils.isEmpty("null")}")
        LogUtils.wTag("statusBarHeight", "${ScreenUtils.getStatusBarHeight()}")
        LogUtils.wTag("navBarHeight", "${ScreenUtils.getHeightOfNavigationBar(this)}")
        viewBinding.itemView.getEditText().nameFormatNoSpace()
        viewBinding.itemView2.moneyFormat()
        liveObserve<String>("change") {
            ZToastUtils.showShort(it)
        }
        livePostValue("name", "你是二狗子啊？")
        initData()

        val view = FloatingView(this)
            .setMarginHorizontal(10f.dp2px)
            .setTopMargin(10f.dp2px)
            .setBottomMargin(10f.dp2px)
            .setIsAutoScreen(true)
            .setContentView(TextView(this).apply {
                setBackgroundColor(Color.RED)
                text = "拖动"
                gravity = Gravity.CENTER
                textSize = 14f
                setTextColor(R.color.color_white.color())
            })
        view.onClickListener = { "点击了浮框".toast() }
        viewBinding.iFrame.addView(view, FrameLayout.LayoutParams(100f.dp2px, 70f.dp2px).apply {
            leftMargin = 10f.dp2px
            topMargin = com.blankj.utilcode.util.ScreenUtils.getAppScreenHeight() - 150f.dp2px
        })

        val updateService = UpdateService.Builder(this).build()
        updateService.download()

        val cpuArchitecture = CpuArchUtils.getCpuArchitecture()
        Log.i("CPU_ARCHITECTURE", cpuArchitecture)

        //异步处理数据等待完成之后同步得到数据
        val downLatch = CountDownLatch(1)
        lifecycleScope.launch {
            downLatch.countDown()
        }
        try {
            downLatch.await()
        } catch (e: Exception) {
            e.printStackTrace()
        }

        //7h/CaDMRpJBu0FMYDPhJ2qLOFvUFVrtwaM2t4mV3MJl8+XUEM8QvaCYvNZaEC+7+10w6Xyn8D8mt5d61F+Ho45nKbQoZclalhzaNKFYkbypSChbR8xIRI0CbfxYSSwYw/UCN6TVTHoaK8zMWo52OXw==
        val data =
            "{\"locationIp\":\"113.251.78.105\",\"dislikeList\":[{\"adId\":\"1813508853778616322\",\"timestamp\":1721960685705}]}"
        val key = "G1VvYzdlr0q3qCa0iVlCCQ=="
        try {
            LogUtils.e(
                "国4加密",
                Base64.encodeToString(
                    Sm4Util.encrypt(
                        data.toByteArray(),
                        Base64.decode(key, Base64.DEFAULT)
                    ), Base64.DEFAULT
                )
            )
        } catch (e: Throwable) {
            e.printStackTrace()
        }
        /* try {
             val libPath =
                 "${Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)}/app-release.apk"
             val tmpDir = getDir("dex", 0)
             val classloader = DexClassLoader(
                 libPath, tmpDir.absolutePath, null, classLoader
             )
             val classToLoad = classloader.loadClass("com.xyz.startlive.TextShow") as Class
             val myInstance = classToLoad.newInstance()
             val doSomething = classToLoad.getMethod("doSomething")
             doSomething.invoke(myInstance)
         } catch (e: Exception) {
             e.printStackTrace()
         }*/
    }

    override fun onClick(v: View?) {
        gotoAct(ZjConfig.TextNetActivity)
    }

    @SuppressLint("Range")
    private fun initData() {
        viewBinding.apply {
            btnToMenu.clickSingleListener {
                gotoAct(ZjConfig.MainActivity)
            }
            btnNet.clickSingleListener(this@SplashActivity)
            btnLogin.setOnClickListener {
                gotoAct(ZjConfig.LoginActivity) {
                    putString("name", "是不是很气")
                }
            }
            btnList.setOnClickListener {
                gotoAct(ZjConfig.ListActivity)
            }
            btnDialog.setOnClickListener {
                TestDialog().show(supportFragmentManager)
            }
            btnWxPay.setOnClickListener {
                gotoActAnimation(TestWxPayActivity::class.java, viewBinding.btnWxPay)
            }
            btnALiPay.setOnClickListener {
                gotoAct(TestALiPayActivity::class.java) {
                    putExtra("name", "你很帅")
                }
            }
            btnPicture.setOnClickListener {
                launcher.launch(this@SplashActivity, PictureActivity::class.java) {
                    putExtra("name", "你好!!!")
                }
            }
            btnPopupWindow.setOnClickListener {
                openPopupWindow()
            }
            btnNavigation.setOnClickListener {
                gotoAct(NavigationActivity::class.java)
            }
            btnRedBank.setOnClickListener {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    gotoAct(NumberPickerActivity::class.java)
                }
            }
            btnMotion.setOnClickListener {
                gotoAct(MotionActivity::class.java)
            }
            btnTab.setOnClickListener {
                gotoAct(ScrollViewTabActivity::class.java)
            }
            btnProgress.setOnClickListener {
                gotoAct(ProgressActivity::class.java)
            }
            btnRxFFmpeg.setOnClickListener {
                gotoAct(RxFFmpegActivity::class.java)
            }
            btnX5.setOnClickListener {
                gotoAct(X5Activity::class.java)
            }
            btnShare.setOnClickListener {
                gotoAct(ShareActivity::class.java)
            }
            btnMock.setOnClickListener {
                gotoAct(MockLocationActivity::class.java)
            }
            btnWebRTC.setOnClickListener {
                requestPermission(
                    listOf(
                        Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO
                    )
                ) { isAllGranted, _, _, _ ->
                    if (isAllGranted) {
                        gotoAct(WebRtcActivity::class.java)
                    }
                }
            }
            btnViewPager2.setOnClickListener {
                gotoAct(ViewPager2Activity::class.java)
            }
            btnRecord.setOnClickListener {
                requestPermission(
                    listOf(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.RECORD_AUDIO
                    )
                ) { isAllGranted, _, _, _ ->
                    if (isAllGranted) {
                        gotoAct(AudioActivity::class.java)
                    }
                }
            }
            btnChat.setOnClickListener {
                gotoAct(ChatActivity::class.java)
            }
            btnTts.setOnClickListener {
                gotoAct(TtsActivity::class.java)
            }
            btnLive.setOnClickListener {
                requestPermission(sdcardCamera) { isAllGranted, _, _, _ ->
                    if (isAllGranted) {
                        gotoAct(LiveActivity::class.java)
                    }
                }
            }
            btnRecordLive.setOnClickListener {
                gotoAct(RecordLiveActivity::class.java)
            }
            btnCamera2.setOnClickListener {
                requestPermission(sdcardCamera) { isAllGranted, _, _, _ ->
                    if (isAllGranted) {
                        gotoAct(Camera2Activity::class.java)
                    }
                }
            }
            btnTextAd.setOnClickListener {
                requestPermission(PerConfig.readPhone) { isAllGranted, _, _, _ ->
                    if (isAllGranted) {
                        gotoAct(TextAdActivity::class.java)
                    }
                }
            }
            btnGt.setOnClickListener {
                // 检查通知权限是否已经授予 - android 11 以上需要开启权限
                val granted =
                    NotificationManagerCompat.from(this@SplashActivity).areNotificationsEnabled()
                if (!granted) {
                    // 请求通知权限
                    val intent = Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
                        .putExtra(Settings.EXTRA_APP_PACKAGE, packageName)
                    startActivity(intent)
                } else gotoAct(GTActivity::class.java)
            }
            btnCreateFile.setOnClickListener {
                launcher.gotoFileAndroid11(this@SplashActivity) {
                    requestPermission(PerConfig.sdcard) { isAllGranted, _, _, _ ->
                        if (isAllGranted) {
                            val file =
                                File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).absolutePath + File.separator + "myText")
                            if (!file.exists()) {
                                val status = if (file.mkdirs()) "创建成功" else "创建失败"
                                status.toast()
                            } else {
                                "文件夹已存在".toast()
                            }
                        } else {
                            "拒绝权限申请".toast()
                        }
                    }
                }
            }
            btnRecordScreen.setOnClickListener {
                requestPermission(PerConfig.sdcard_audio) { isAllGranted, _, _, _ ->
                    if (isAllGranted) {
                        gotoAct(RecordScreenActivity::class.java)
                    }
                }
            }
            btnProcess.setOnClickListener {
                gotoActDocument(ProcessActivity::class.java, "process")
            }
            btnWindow.setOnClickListener {
                val file = File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
                    "tata.apk"
                )
                deleteAndRecreateFile(file)
            }
            btnSortList.setOnClickListener {
                gotoAct(SortLetterActivity::class.java)
            }
        }
    }

   private fun deleteAndRecreateFile(file: File) {
       /* if (file.exists()) {
            // 尝试删除文件
            if (file.delete()) {
                println("File deleted successfully.")
            } else {
                println("Failed to delete the file.")
                return
            }
        }*/

        // 刷新媒体库（适用于外部存储）
        MediaScannerConnection.scanFile(this, arrayOf<String>(file.absolutePath), null, null)
        // 尝试创建新文件
        try {
            if (file.createNewFile()) {
                println("New file created successfully.")
            } else {
                println("Failed to create a new file.")
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    fun clickTest(view: View) {
        gotoAct(TestActivity::class.java)
    }

    private fun openPopupWindow() {
        if (DoubleUtils.isFastDoubleClick()) return
        BasePopWindow(this)
            .createView(
                R.layout.layout_pop,
                SizeUtils.dp2px(150f),
                FrameLayout.LayoutParams.WRAP_CONTENT
            )
            .showAsDropDown(viewBinding.btnPopupWindow, 0, 0, Gravity.TOP)
    }

    override fun onResume() {
        super.onResume()
        getClipboard()
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (hasFocus && Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            getClipboard()
        }
    }

    private fun getClipboard() {
        //获取系统剪贴板服务
        val clipboardManager = this.getSystemService(CLIPBOARD_SERVICE) as? ClipboardManager
        if (null != clipboardManager) {
            LogUtils.e("content22: ${clipboardManager.text}")
            // 获取剪贴板的剪贴数据集
            val clipData = clipboardManager.primaryClip;clipboardManager.hasPrimaryClip()
            if (null != clipData && clipData.itemCount > 0) {
                // 从数据集中获取（粘贴）第一条文本数据
                val item = clipData.getItemAt(0)
                if (null != item) {
                    val content = item.text.toString()
                    LogUtils.e("content: $content")
                    // 清除剪贴板
                    val clip = ClipData.newPlainText("", "")
                    clipboardManager.setPrimaryClip(clip)
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        launcher.unregister()
    }
}